import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import Dashboard from '../views/Dashboard.vue'
import Login from '../views/Login.vue'

import Building from '../views/dormitory/Building.vue'
import Room from '../views/dormitory/Room.vue'
import Allocation from '../views/dormitory/Allocation.vue'
import RoomLabel from '../views/dormitory/RoomLabel.vue'
import Bed from '../views/dormitory/Bed.vue'

import Student from '../views/user/Student.vue'
import Profession from '../views/user/Profession.vue'
import Maintainer from '../views/user/Maintainer.vue'

import Repair from '../views/Repair.vue'
import CreateRepair from '../views/repair/CreateRepair.vue'
import RepairList from '../views/repair/RepairList.vue'

import Violation from '../views/score/Violation.vue'
import Hygiene from '../views/score/Hygiene.vue'



const routes = [
  { 
    path: '/login', 
    name: 'Login', 
    component: Login
  },
  {
    path: '/',
    name: 'Home',
    component: Dashboard
  },
  {
    path: '/dormitory/building',
    name: 'Building',
    component: Building,
  },
  {
    path: '/dormitory/room',
    name: 'Room',
    component: Room,
  },
  {
    path: '/dormitory/allocation',
    name: 'Allocation',
    component: Allocation,
  },
  {
    path: '/dormitory/room-label',
    name: 'RoomLabel',
    component: RoomLabel,
  },
  {
    path: '/dormitory/bed',
    name: 'Bed',
    component: Bed,
  },
  {
    path: '/user/student',
    name: 'Student',
    component: Student,
  },
  {
    path: '/user/profession',
    name: 'Profession',
    component: Profession,
  },
  {
    path: '/user/maintainer',
    name: 'Maintainer',
    component: Maintainer,
  },
  {
    path: '/system/user',
    name: 'SystemUser',
    component: () => import('../views/system/User.vue'),
  },
  {
    path: '/system/role',
    name: 'SystemRole',
    component: () => import('../views/system/Role.vue'),
  },
  {
    path: '/system/permission',
    name: 'SystemPermission',
    component: () => import('../views/system/Permission.vue'),
  },

  {
    path: '/repair',
    name: 'Repair',
    component: Repair,
  },
  {
    path: '/repair/create',
    name: 'CreateRepair',
    component: CreateRepair,
  },
  {
    path: '/repair/list',
    name: 'RepairList',
    component: RepairList,
  },
  {
    path: '/score/violation',
    name: 'Violation',
    component: Violation,
  },
  {
    path: '/score/hygiene',
    name: 'Hygiene',
    component: Hygiene,
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由守卫：只有登录时才可以访问其他页面
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 如果访问登录页面，直接放行
  if (to.name === 'Login') {
    next()
    return
  }
  
  // 如果用户已登录，放行
  if (authStore.isLoggedIn) {
    next()
    return
  }
  
  // 如果用户未登录，重定向到登录页
  next({ name: 'Login' })
})

export default router